package com.ty.utils;

import com.ty.entity.AdminEntity;
import com.ty.resp.CommonResp;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : txy
 * @since : 2024/2/1 9:54
 */
@Component
public class JwtUtil<T> {

    @Value("${jwt.token.secretKey}")
    private String secretKey;

    @Value("${jwt.token.expiration}")
    private Long expiration;

    public String createToken(T sysUser) {
        JwtBuilder builder = Jwts.builder();
        Map<String, Object> map = new HashMap<>();
        map.put("user", sysUser);
        return builder.claims(map)//添加负载
                .id(UUID.randomUUID().toString())//tokenId
                .expiration(new Date(new Date().getTime() + expiration))//过期时间
                .issuedAt(new Date())//发布时间
                .issuer("com.ty")//发布作者
                .subject("系统登录Token")//标题
                //签名密钥，大于32个字符
                .signWith(Keys.hmacShaKeyFor(secretKey.getBytes()))
                .compact();
    }

    public CommonResp<Jws<Claims>> parseClaim(String token) {
        CommonResp result = new CommonResp();
        result.setSuccess(false);
        try {
            Jws<Claims> claims = Jwts.parser()
                    .verifyWith(Keys.hmacShaKeyFor(secretKey.getBytes()))
                    .build()
                    .parseSignedClaims(token);
            result.setContent(claims);
            result.setSuccess(true);
            return result;
        } catch (SignatureException e) {
            result.setCode(403);
            result.setMessage("签名不符合要求或者没有");
        } catch (ExpiredJwtException e) {
            result.setCode(401);
            result.setMessage("签名已经过期");
        } catch (MalformedJwtException e) {
            result.setCode(403);
            result.setMessage("token被篡改");
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("token验证失败");
        }
        return result;
    }


    public CommonResp<T> parsePayload(String token) {
        CommonResp<Jws<Claims>> result = parseClaim(token);
        CommonResp result1 = new CommonResp();
        if (result.getSuccess()) {
            Map user = result.getContent().getPayload().get("user", Map.class);
            result1.setContent(user);
            result1.setCode(200);
            result1.setSuccess(true);
        }else {
            result1.setMessage(result.getMessage());
        }
        return result1;
    }
}



